#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'binpo'

import db
import json
import sys,os
import decimal
from datetime import *

class CJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        else:
            return json.JSONEncoder.default(self, obj)

import os.path
import tornado.auth
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from tornado.web import RequestHandler

define("port", default=9200, help="run on the given port", type=int)

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [

            (r'/', IndexHandler),
            (r'/json/(.*)/', DataProvider),
            (r'/query', QueryProvider),
            (r'/showCreate', TableMetaProvider),
            (r"/([\w\W]*)", IndexHandler),
        ]

        settings = dict(
            blog_title=u"MySQL OPTS",
            template_path=os.path.join(os.path.dirname(__file__), "html"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies=True,
            autoescape=None,
            cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
            login_url="/auth/login",
            debug=True,
        )
        tornado.web.Application.__init__(self, handlers, **settings)

        # Have one global connection to the blog DB across all handlers
        # self.db = torndb.Connection(
        #     host=options.mysql_host, database=options.mysql_database,
        #     user=options.mysql_user, password=options.mysql_password)
import urlparse
class BaseHandler(RequestHandler):
    def check_xsrf_cookie(self):
        pass

    def prepare(self):
        self.get_paras_dict()
    def get_paras_dict(self):
        """
        :todo 获取请求参数 字典
        """
        if self.request.method=='GET':
            query = self.request.query
            self.qdict = urlparse.parse_qs(query)
            for k, v in self.qdict.items():
                self.qdict[k] = v and v[0] or ''
        elif self.request.method in ('POST','PUT','DELETE'):
            self.qdict={}
            query = self.request.arguments
            for key in query.keys():
                self.qdict[key]=len(query[key])!=1 and query[key] or (query[key][0] and query[key][0] or '')


class DataProvider(BaseHandler):
    pass


class QueryProvider(BaseHandler):

    def post(self, *args, **kwargs):

        if self.qdict.get('queryType') == 'where':
            values = db.queryAll(self.qdict.get('tableName'), self.qdict.get('condition'), self.qdict.get('orderCondition'))
            cols = db.getColumns(self.qdict.get('tableName'))
        elif self.qdict.get('queryType') == 'full':
            cols = []
            values = db.execQuery(self.qdict.get('condition'))
        returnMap = {"v":values,"k":cols}
        self.write( json.dumps(returnMap,cls=CJsonEncoder))
    def GET(self,param):
        return param


class TableMetaProvider(BaseHandler):
    def post(self, *args, **kwargs):
        result = db.execQuery("show create table "+ self.qdict.get('tableName'))
        self.write(json.dumps(result))
    def get(self, *args, **kwargs):
        self.write(json.dumps(self.qdict))


class IndexHandler(RequestHandler):

    def get(self, *args, **kwargs):
        tables=db.initTables()
        self.render('index.html',tables=tables)


    def post(self, *args, **kwargs):
        pass


class NotFoundHandler(RequestHandler):
    def get(self):
        self.render('404.html')
def main():
    tornado.options.parse_command_line()
    # tornado.process.fork_processes(0)
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)

    # import tornado.process
    print 'http://localhost:',options.port
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    main()


